<template>
  <el-dialog v-model="dialogVisible" width="80vw" :close-on-click-modal="false" @close="handleClose">
    <Title :title="`查看结果/手动分配分组：${groupInfo.groupName}`" />
    <div class="dialog-container">
      <!-- 搜索表单 -->
      <el-form :model="queryParams" :inline="true" class="search-form">
        <el-form-item label="毕设名称" prop="teamName">
          <el-input v-model="queryParams.teamName" placeholder="请输入毕设名称" clearable style="width: 200px" @keyup.enter="handleSearch" />
        </el-form-item>

        <el-form-item label="学生学号" prop="stuId">
          <el-input v-model="queryParams.stuId" placeholder="请输入学生学号" clearable style="width: 200px" @keyup.enter="handleSearch" />
        </el-form-item>

        <el-form-item label="指导老师" prop="teacherName">
          <el-input v-model="queryParams.teacherName" placeholder="请输入指导老师名字" clearable style="width: 200px" @keyup.enter="handleSearch" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleSearch">搜索</el-button>
          <el-button icon="Refresh" @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 队伍列表表格 -->
      <el-table v-loading="loading" :data="teamList" border class="team-table">
        <el-table-column type="index" label="序号" width="60" align="center" />

        <el-table-column label="毕设名称" align="center" show-overflow-tooltip>
          <template #default="{ row }">
            {{ row.teamName || '-' }}
          </template>
        </el-table-column>

        <el-table-column label="队长" align="center">
          <template #default="{ row }">
            {{ getLeaderName(row) }}
          </template>
        </el-table-column>

        <el-table-column label="队伍成员" align="center">
          <template #default="{ row }">
            <el-popover placement="top" :width="200" trigger="hover">
              <template #reference>
                <el-tag type="info">{{ row.studentTeams?.length || 0 }} 人</el-tag>
              </template>
              <div class="member-list">
                <div v-for="member in row.studentTeams" :key="member.studentId" class="member-item">
                  <el-tag size="small" :type="member.isLeader === '1' ? 'success' : ''">
                    {{ member.student?.user?.nickName || member.student?.userName }}
                    <span v-if="member.isLeader === '1'">(队长)</span>
                  </el-tag>
                </div>
              </div>
            </el-popover>
          </template>
        </el-table-column>

        <el-table-column label="查看详情" align="center">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleViewIntro(row)">查看</el-button>
          </template>
        </el-table-column>

        <el-table-column label="第一志愿" align="center">
          <template #default="{ row }">
            <span v-if="getFirstVolunteer(row)">
              {{ getFirstVolunteer(row) }}
            </span>
            <span v-else class="text-muted">未填报</span>
          </template>
        </el-table-column>

        <el-table-column label="查看志愿" align="center">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleViewVolunteers(row)">查看</el-button>
          </template>
        </el-table-column>

        <el-table-column label="匹配教师" width="300" align="center">
          <template #default="{ row }">
            <!-- 已分配：显示教师名称+取消按钮 -->
            <div v-if="row.teamTeachers.find((t) => t.selectFlag == '1')?.teacherId" class="allocated-teacher">
              <el-tag type="success" size="large">
                {{ getTeacherName(row.teamTeachers.find((t) => t.selectFlag == '1')?.teacherId) }}
              </el-tag>
              <el-button link type="danger" size="small" :loading="row.canceling" @click="handleCancelAllocate(row)">取消选择</el-button>
            </div>

            <!-- 未分配：显示选择框 -->
            <el-select v-else v-model="row.selectedTeacherId" placeholder="请选择教师" clearable size="large" filterable :loading="row.allocating" @change="handleTeacherSelect(row)">
              <el-option v-for="teacher in getSortedTeachersForTeam(row)" :key="teacher.teacherId" :label="teacher.teacherName" :value="teacher.teacherId">
                <div class="teacher-option">
                  <span class="teacher-name">{{ teacher.teacherName }}</span>
                  <span class="teacher-info">
                    <span class="teacher-slots">(剩余 {{ teacher.availableSlots || 0 }} 个名额)</span>
                    <span class="teacher-score" v-if="teacher.matchScore > 0">匹配分: {{ teacher.matchScore.toFixed(1) }}</span>
                  </span>
                </div>
              </el-option>
            </el-select>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
      </div>
    </template>

    <!-- 查看简介对话框 -->
    <team-detail-dialog ref="detailDialogRef" />
    <!-- 查看志愿对话框 -->
    <team-volunteer-dialog ref="volunteerDialogRef" />
  </el-dialog>
</template>

<script setup>
import { ref, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getAvailableTeachers, manualAllocate, cancelAllocate } from '@/api/allocate'
import { listTeam } from '@/api/team'
import Title from '@/components/Title/index.vue'
import TeamDetailDialog from '@/views/team/components/TeamDetailDialog.vue'
import TeamVolunteerDialog from './TeamVolunteerDialog.vue'

const dialogVisible = ref(false)
const loading = ref(false)
const groupInfo = ref(null)
const teamList = ref([])
const availableTeachers = ref([])
const detailDialogRef = ref(null)
const volunteerDialogRef = ref(null)

// 搜索参数
const queryParams = ref({
  teamName: '',
  stuId: '',
  teacherName: ''
})

// 获取队长姓名
const getLeaderName = (team) => {
  const leader = team.studentTeams?.find((s) => s.isLeader === '1')
  return leader?.student?.user?.nickName || leader?.student?.userName || '-'
}

// 获取第一志愿教师名称
const getFirstVolunteer = (team) => {
  const firstVolunteer = team.teamTeachers?.find((v) => v.sort === 1)
  return firstVolunteer?.teacher?.user?.nickName || ''
}

// 根据教师ID获取教师名称
const getTeacherName = (teacherId) => {
  const teacher = availableTeachers.value.find((t) => t.teacherId === teacherId)
  return teacher?.teacherName || '未知教师'
}

// 计算队伍与教师的匹配分数
const calculateMatchScore = (team, teacher) => {
  const teacherMax = groupInfo.value?.teacherMax || 5
  let studentScore = 0 // 学生对教师的志愿分数
  let teacherScore = 0 // 教师对学生的志愿分数

  // 1. 计算学生对教师的志愿分数
  // 在队伍的 teamTeachers 中查找该教师，排除 sort 为 0, 999, 1000
  const studentVolunteer = team.teamTeachers?.find(
    (tt) => tt.teacherId === teacher.teacherId && ![0, 999, 1000].includes(tt.sort)
  )
  if (studentVolunteer) {
    // 第一志愿(sort=1)得 teacherMax 分，第二志愿得 teacherMax-1 分，依次递减
    studentScore = teacherMax - (studentVolunteer.sort - 1)
  }

  // 2. 计算教师对学生的志愿分数
  // 在教师的 volunteers 中查找该队伍，排除 sort 为 0, 999, 1000
  const teacherVolunteer = teacher.volunteers?.find(
    (v) => v.teamId === team.teamId && ![0, 999, 1000].includes(v.sort)
  )
  if (teacherVolunteer) {
    // 教师的志愿分数需要 * 1.1
    teacherScore = (teacherMax - (teacherVolunteer.sort - 1)) * 1.1
  }

  return studentScore + teacherScore
}

// 获取排序后的教师列表（按匹配分数降序）
const getSortedTeachersForTeam = (team) => {
  return availableTeachers.value
    .map((teacher) => ({
      ...teacher,
      matchScore: calculateMatchScore(team, teacher)
    }))
    .sort((a, b) => b.matchScore - a.matchScore)
}

// 打开对话框
const openDialog = async (group) => {
  groupInfo.value = group
  dialogVisible.value = true
  await Promise.all([loadTeamList(), loadAvailableTeachers()])
}

// 加载队伍列表
const loadTeamList = async () => {
  loading.value = true
  teamList.value = []
  try {
    const params = {
      groupId: groupInfo.value.groupId,
      pageNum: 1,
      pageSize: 9999,
      ...queryParams.value
    }
    const res = await listTeam(params)
    if (res.code === 200) {
      teamList.value = (res.data.rows || []).map((team) => ({
        ...team,
        selectedTeacherId: null, // 用于未分配时的选择
        allocating: false, // 分配中状态
        canceling: false // 取消中状态
      }))
    }
  } catch (error) {
    console.error('加载队伍列表失败:', error)
    ElMessage.error('加载队伍列表失败')
  } finally {
    loading.value = false
  }
}

// 加载空闲教师列表
const loadAvailableTeachers = async () => {
  try {
    const res = await getAvailableTeachers(groupInfo.value.groupId)
    if (res.code === 200) {
      availableTeachers.value = res.data || []
    }
  } catch (error) {
    console.error('加载教师列表失败:', error)
    ElMessage.error('加载教师列表失败')
  }
}

// 选择教师（立即分配）
const handleTeacherSelect = async (row) => {
  if (!row.selectedTeacherId) return

  row.allocating = true
  try {
    const res = await manualAllocate({
      teamId: row.teamId,
      teacherId: row.selectedTeacherId
    })

    if (res.code === 200) {
      ElMessage.success('分配成功')
      // 更新队伍的教师ID
      row.teacherId = row.selectedTeacherId
      row.selectedTeacherId = null

      // 更新队伍的教师名称
      row.teacherName = getTeacherName(row.selectedTeacherId)
      // 刷新队伍列表（因为教师ID可能变化）
      await loadTeamList()
      // 刷新空闲教师列表（因为容量可能变化）
      await loadAvailableTeachers()

      emit('success')
    } else {
      ElMessage.error(res.msg || '分配失败')
      row.selectedTeacherId = null
    }
  } catch (error) {
    console.error('分配失败:', error)
    ElMessage.error('分配失败，请稍后重试')
    row.selectedTeacherId = null
  } finally {
    row.allocating = false
  }
}

// 取消分配
const handleCancelAllocate = async (row) => {
  try {
    await ElMessageBox.confirm(`确定要取消 "${row.teamName}" 与 "${getTeacherName(row.teamTeachers.find((t) => t.selectFlag == '1').teacherId)}" 的匹配吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    row.canceling = true
    try {
      await cancelAllocate({
        teamId: row.teamId,
        teacherId: row.teamTeachers.find((t) => t.selectFlag == '1').teacherId
      })

      ElMessage.success('已取消分配')
      // 清除教师ID
      row.teacherId = null
      await loadTeamList()

      // 刷新空闲教师列表
      await loadAvailableTeachers()

      emit('success')
    } catch (error) {
      console.error('取消分配失败:', error)
      ElMessage.error('取消分配失败，请稍后重试')
    } finally {
      row.canceling = false
    }
  } catch {
    // 用户取消操作
  }
}

// 查看简介
const handleViewIntro = (team) => {
  detailDialogRef.value.openDialog(team)
}

// 查看志愿
const handleViewVolunteers = (team) => {
  volunteerDialogRef.value.openDialog(team)
}

// 搜索按钮
const handleSearch = () => {
  loadTeamList()
}

// 重置按钮
const handleReset = () => {
  queryParams.value = {
    teamName: '',
    stuId: '',
    teacherName: ''
  }
  loadTeamList()
}

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false
  // 重置搜索参数
  queryParams.value = {
    teamName: '',
    stuId: '',
    teacherName: ''
  }
}

const emit = defineEmits(['success'])

defineExpose({
  openDialog
})
</script>

<style scoped lang="scss">
.dialog-container {
  padding: 16px 0;
  height: 72vh;
}

.search-form {
  border-radius: 4px;
}

.manual-allocate-container {
  height: 72vh;
  .mb-16 {
    margin-bottom: 16px;
  }

  .stats-bar {
    display: flex;
    gap: 16px;
    margin-bottom: 16px;
    padding: 12px;
    background: #f5f7fa;
    border-radius: 4px;
  }

  .team-table {
    .text-muted {
      color: #909399;
    }

    .allocated-teacher {
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 12px;
    }

    .teacher-count {
      margin-left: 8px;
      font-size: 12px;
      color: #909399;
    }
  }
}

// 教师选项样式
.teacher-option {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;

  .teacher-name {
    font-size: 14px;
    font-weight: 500;
  }

  .teacher-info {
    display: flex;
    align-items: center;
    gap: 12px;
    font-size: 12px;
  }

  .teacher-slots {
    color: #909399;
  }

  .teacher-score {
    color: var(--el-color-primary);
    font-weight: 600;
  }
}

.member-list {
  .member-item {
    margin-bottom: 8px;

    &:last-child {
      margin-bottom: 0;
    }
  }
}
</style>
